package com.ydl.iec.test;

import com.ydl.iec.iec104.common.BasicInstruction104;
import com.ydl.iec.iec104.config.Iec104Config;
import com.ydl.iec.iec104.enums.TypeIdentifierEnum;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.message.MessageInfo;
import com.ydl.iec.iec104.server.handler.ChannelHandler;
import com.ydl.iec.iec104.server.handler.DataHandler;
import com.ydl.iec.util.ByteUtil;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

/**
 * @Author : 汪洋
 * @CreateTime : 2023/11/29
 * @Description :
 * @Version : v1.0
 */
@AllArgsConstructor
public class SysDataHandler implements DataHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysDataHandler.class);

    private Iec104Config iec104Config;

    @Override
    public void handlerAdded(ChannelHandler ctx) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandler ctx, MessageDetail ruleDetail104) throws Exception {
        LOGGER.info("收到信息：" + ruleDetail104.toString());

        if (iec104Config.getType() == 0x64) {
            doYaoCe(ruleDetail104);
            ctx.writeAndFlush(BasicInstruction104.getEndGeneralCallRuleDetail104());
        } else {
            doYaoMai(ruleDetail104);
            ctx.writeAndFlush(BasicInstruction104.get2EndGeneralCallRuleDetail104());
        }
    }

    public static void doYaoMai(MessageDetail ruleDetail104) {
        List<MessageInfo> messages = ruleDetail104.getMessages();
        if (messages == null || messages.size() == 0) {
            return;
        }
        for (MessageInfo messageInfo : messages) {
            int messageAddress = messageInfo.getMessageAddress();
            byte[] messageInfos = messageInfo.getMessageInfos();
            int value = ByteUtil.byteArrayToInt(new byte[]{messageInfos[3], messageInfos[2],messageInfos[1], messageInfos[0]});
            LOGGER.info("YAOMIAO->地址：" + messageAddress + "  value:" + value);
        }
    }

    public static void doYaoCe(MessageDetail ruleDetail104) {
        List<MessageInfo> messages = ruleDetail104.getMessages();
        if (messages == null || messages.size() == 0) {
            return;
        }
        for (MessageInfo messageInfo : messages) {
            LOGGER.info("YAOMIAO->地址：" + messageInfo);
        }
    }

}
